<template>
	<view class="files-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" @tap="goBack">
				<text class="back-icon">‹</text>
			</view>
			<view class="header-center">
				<text class="header-title">班级文件</text>
			</view>
			<view class="header-right">
				<uni-icons type="plus" size="18" color="#fff" @tap="showUploadModal"></uni-icons>
			</view>
		</view>

		<!-- 搜索栏 -->
		<view class="search-section">
			<view class="search-bar">
				<uni-icons type="search" size="16" color="#999"></uni-icons>
				<input 
					class="search-input" 
					v-model="searchKeyword" 
					placeholder="搜索文件..." 
					@input="onSearch"
				/>
			</view>
		</view>

		<!-- 文件分类标签 -->
		<view class="category-tabs">
			<scroll-view class="tabs-scroll" scroll-x="true">
				<view class="tabs-container">
					<text 
						class="category-tab" 
						:class="{ active: currentCategory === 'all' }"
						@tap="setCategory('all')"
					>全部</text>
					<text 
						class="category-tab" 
						:class="{ active: currentCategory === 'document' }"
						@tap="setCategory('document')"
					>文档</text>
					<text 
						class="category-tab" 
						:class="{ active: currentCategory === 'image' }"
						@tap="setCategory('image')"
					>图片</text>
					<text 
						class="category-tab" 
						:class="{ active: currentCategory === 'video' }"
						@tap="setCategory('video')"
					>视频</text>
					<text 
						class="category-tab" 
						:class="{ active: currentCategory === 'other' }"
						@tap="setCategory('other')"
					>其他</text>
				</view>
			</scroll-view>
		</view>

		<!-- 文件列表 -->
		<view class="files-list">
			<view class="list-header">
				<text class="list-title">文件列表 ({{ filteredFiles.length }})</text>
				<view class="sort-options">
					<text 
						class="sort-option" 
						:class="{ active: currentSort === 'time' }"
						@tap="setSort('time')"
					>时间</text>
					<text 
						class="sort-option" 
						:class="{ active: currentSort === 'name' }"
						@tap="setSort('name')"
					>名称</text>
					<text 
						class="sort-option" 
						:class="{ active: currentSort === 'size' }"
						@tap="setSort('size')"
					>大小</text>
				</view>
			</view>

			<scroll-view class="files-scroll" scroll-y="true">
				<view 
					v-for="(file, index) in sortedFiles" 
					:key="index" 
					class="file-item"
					@tap="showFileDetail(file)"
				>
					<view class="file-icon">
						<uni-icons :type="getFileIcon(file.type)" size="24" :color="getFileColor(file.type)"></uni-icons>
					</view>
					<view class="file-info">
						<text class="file-name">{{ file.name }}</text>
						<view class="file-meta">
							<text class="file-size">{{ formatFileSize(file.size) }}</text>
							<text class="file-time">{{ file.uploadTime }}</text>
						</view>
						<view class="file-uploader">
							<text class="uploader-text">上传者：{{ file.uploader }}</text>
						</view>
					</view>
					<view class="file-actions">
						<uni-icons type="download" size="20" color="#007AFF" @tap.stop="downloadFile(file)"></uni-icons>
						<uni-icons type="trash" size="20" color="#FF3B30" @tap.stop="deleteFile(file)"></uni-icons>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 上传文件弹窗 -->
		<view v-if="showUpload" class="modal-overlay" @tap="closeUploadModal">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">上传文件</text>
					<uni-icons type="close" size="20" color="#999" @tap="closeUploadModal"></uni-icons>
				</view>
				<view class="modal-body">
					<view class="upload-area" @tap="chooseFile">
						<uni-icons type="cloud-upload" size="48" color="#007AFF"></uni-icons>
						<text class="upload-text">点击选择文件</text>
						<text class="upload-hint">支持文档、图片、视频等格式</text>
					</view>
					<view v-if="selectedFile" class="selected-file">
						<view class="file-preview">
							<uni-icons :type="getFileIcon(selectedFile.type)" size="24" :color="getFileColor(selectedFile.type)"></uni-icons>
							<text class="preview-name">{{ selectedFile.name }}</text>
						</view>
						<text class="preview-size">{{ formatFileSize(selectedFile.size) }}</text>
					</view>
					<view class="input-group">
						<text class="input-label">文件分类</text>
						<picker 
							mode="selector" 
							:range="fileCategories" 
							:value="newFile.categoryIndex" 
							@change="onCategoryChange"
						>
							<view class="picker-field">
								<text class="picker-text">{{ fileCategories[newFile.categoryIndex] || '请选择分类' }}</text>
								<uni-icons type="down" size="16" color="#999"></uni-icons>
							</view>
						</picker>
					</view>
					<view class="input-group">
						<text class="input-label">文件描述</text>
						<textarea 
							class="textarea-field" 
							v-model="newFile.description" 
							placeholder="请输入文件描述"
							:maxlength="200"
						></textarea>
						<text class="char-count">{{ newFile.description.length }}/200</text>
					</view>
				</view>
				<view class="modal-footer">
					<view class="modal-btn cancel-btn" @tap="closeUploadModal">
						<text class="btn-text">取消</text>
					</view>
					<view class="modal-btn confirm-btn" @tap="uploadFile">
						<text class="btn-text">上传</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue';

	// 文件列表
	const filesList = ref([
		{
			id: 1,
			name: '高等数学教材.pdf',
			type: 'document',
			size: 2048576, // 2MB
			uploadTime: '2024-01-15 14:30',
			uploader: '张教授',
			description: '第一章微积分基础教材',
			url: '/static/files/math-textbook.pdf'
		},
		{
			id: 2,
			name: '课程PPT.pptx',
			type: 'document',
			size: 5120000, // 5MB
			uploadTime: '2024-01-14 10:20',
			uploader: '李老师',
			description: '微积分课程演示文稿',
			url: '/static/files/course-ppt.pptx'
		},
		{
			id: 3,
			name: '实验指导书.docx',
			type: 'document',
			size: 1024000, // 1MB
			uploadTime: '2024-01-13 16:45',
			uploader: '王老师',
			description: '程序设计实验指导书',
			url: '/static/files/lab-guide.docx'
		},
		{
			id: 4,
			name: '班级合影.jpg',
			type: 'image',
			size: 3072000, // 3MB
			uploadTime: '2024-01-12 09:15',
			uploader: '班长',
			description: '班级第一次聚会合影',
			url: '/static/files/class-photo.jpg'
		},
		{
			id: 5,
			name: '课程录像.mp4',
			type: 'video',
			size: 52428800, // 50MB
			uploadTime: '2024-01-11 15:30',
			uploader: '张教授',
			description: '微积分第一课录像',
			url: '/static/files/course-video.mp4'
		}
	]);

	// 文件分类
	const fileCategories = ref(['文档', '图片', '视频', '其他']);

	// 搜索和筛选
	const searchKeyword = ref('');
	const currentCategory = ref('all');
	const currentSort = ref('time');

	// 上传文件相关
	const showUpload = ref(false);
	const selectedFile = ref(null);
	const newFile = ref({
		categoryIndex: 0,
		description: ''
	});

	// 返回上一页
	const goBack = () => {
		uni.navigateBack({
			fail: () => {
				// 如果返回失败，跳转到班级页面
				uni.navigateTo({
					url: '/pages/class/class'
				});
			}
		});
	};

	// 设置分类
	const setCategory = (category: string) => {
		currentCategory.value = category;
	};

	// 设置排序
	const setSort = (sort: string) => {
		currentSort.value = sort;
	};

	// 搜索
	const onSearch = () => {
		// 实时搜索功能
	};

	// 筛选后的文件
	const filteredFiles = computed(() => {
		let files = filesList.value;

		// 按分类筛选
		if (currentCategory.value !== 'all') {
			files = files.filter(file => file.type === currentCategory.value);
		}

		// 按关键词搜索
		if (searchKeyword.value.trim()) {
			const keyword = searchKeyword.value.toLowerCase();
			files = files.filter(file => 
				file.name.toLowerCase().includes(keyword) ||
				file.description.toLowerCase().includes(keyword) ||
				file.uploader.toLowerCase().includes(keyword)
			);
		}

		return files;
	});

	// 排序后的文件
	const sortedFiles = computed(() => {
		const files = [...filteredFiles.value];

		switch (currentSort.value) {
			case 'name':
				return files.sort((a, b) => a.name.localeCompare(b.name));
			case 'size':
				return files.sort((a, b) => b.size - a.size);
			case 'time':
			default:
				return files.sort((a, b) => new Date(b.uploadTime).getTime() - new Date(a.uploadTime).getTime());
		}
	});

	// 显示上传文件弹窗
	const showUploadModal = () => {
		showUpload.value = true;
	};

	// 关闭上传文件弹窗
	const closeUploadModal = () => {
		showUpload.value = false;
		selectedFile.value = null;
		newFile.value = {
			categoryIndex: 0,
			description: ''
		};
	};

	// 选择文件
	const chooseFile = () => {
		uni.chooseFile({
			count: 1,
			type: 'all',
			success: (res) => {
				const file = res.tempFiles[0];
				selectedFile.value = {
					name: file.name,
					size: file.size,
					type: getFileType(file.name),
					path: file.path
				};
			},
			fail: (err) => {
				uni.showToast({
					title: '选择文件失败',
					icon: 'none'
				});
			}
		});
	};

	// 分类选择
	const onCategoryChange = (e: any) => {
		newFile.value.categoryIndex = e.detail.value;
	};

	// 上传文件
	const uploadFile = () => {
		if (!selectedFile.value) {
			uni.showToast({
				title: '请先选择文件',
				icon: 'none'
			});
			return;
		}

		// BACKEND REQUIRED: POST /api/class/{classId}/files/upload
		// Request Body: FormData {
		//   file: File,
		//   category: string,
		//   description: string
		// }
		// Response: { success: boolean, data: { id: number, url: string } }

		// 创建新文件记录
		const file = {
			id: filesList.value.length + 1,
			name: selectedFile.value.name,
			type: selectedFile.value.type,
			size: selectedFile.value.size,
			uploadTime: new Date().toLocaleString('zh-CN'),
			uploader: '我',
			description: newFile.value.description,
			url: selectedFile.value.path
		};

		// 添加到列表开头
		filesList.value.unshift(file);

		uni.showToast({
			title: '上传成功',
			icon: 'success'
		});

		closeUploadModal();
	};

	// 获取文件类型
	const getFileType = (fileName: string) => {
		const ext = fileName.split('.').pop()?.toLowerCase();
		if (['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt'].includes(ext)) {
			return 'document';
		} else if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext)) {
			return 'image';
		} else if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) {
			return 'video';
		} else {
			return 'other';
		}
	};

	// 获取文件图标
	const getFileIcon = (type: string) => {
		switch (type) {
			case 'document':
				return 'file-text';
			case 'image':
				return 'image';
			case 'video':
				return 'videocam';
			default:
				return 'file';
		}
	};

	// 获取文件颜色
	const getFileColor = (type: string) => {
		switch (type) {
			case 'document':
				return '#007AFF';
			case 'image':
				return '#34C759';
			case 'video':
				return '#FF9500';
			default:
				return '#8E8E93';
		}
	};

	// 格式化文件大小
	const formatFileSize = (bytes: number) => {
		if (bytes === 0) return '0 B';
		const k = 1024;
		const sizes = ['B', 'KB', 'MB', 'GB'];
		const i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
	};

	// 显示文件详情
	const showFileDetail = (file: any) => {
		uni.showModal({
			title: file.name,
			content: `大小：${formatFileSize(file.size)}\n上传时间：${file.uploadTime}\n上传者：${file.uploader}\n描述：${file.description}`,
			showCancel: false,
			confirmText: '确定'
		});
	};

	// 下载文件
	const downloadFile = (file: any) => {
		// BACKEND REQUIRED: GET /api/class/{classId}/files/{fileId}/download
		// Response: File stream

		uni.showToast({
			title: '开始下载',
			icon: 'success'
		});
	};

	// 删除文件
	const deleteFile = (file: any) => {
		uni.showModal({
			title: '确认删除',
			content: `确定要删除文件"${file.name}"吗？`,
			success: (res) => {
				if (res.confirm) {
					// BACKEND REQUIRED: DELETE /api/class/{classId}/files/{fileId}
					// Response: { success: boolean }

					// 从列表中移除
					const index = filesList.value.findIndex(f => f.id === file.id);
					if (index > -1) {
						filesList.value.splice(index, 1);
					}

					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
				}
			}
		});
	};

	onMounted(() => {
		// BACKEND REQUIRED: GET /api/class/{classId}/files
		// Response: {
		//   files: Array<{
		//     id: number,
		//     name: string,
		//     type: string,
		//     size: number,
		//     uploadTime: string,
		//     uploader: string,
		//     description: string,
		//     url: string
		//   }>
		// }
	});
</script>

<style>
	page {
		background-color: #f5f5f5;
	}

	.files-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部导航栏 */
	.header {
		background: linear-gradient(135deg, #8E8E93, #A2845E);
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.header-left {
		display: flex;
		align-items: center;
		padding: 10rpx;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		min-width: 60rpx;
		min-height: 60rpx;
		justify-content: center;
	}

	.back-icon {
		font-size: 36rpx;
		color: #fff;
		font-weight: bold;
		line-height: 1;
	}

	.header-center {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}

	.header-title {
		font-size: 18px;
		font-weight: 600;
		color: #fff;
	}

	.header-right {
		padding: 10rpx;
	}

	/* 搜索栏 */
	.search-section {
		padding: 20rpx;
		background: #fff;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background: #f5f5f5;
		border-radius: 20rpx;
		padding: 20rpx;
		gap: 20rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	/* 分类标签 */
	.category-tabs {
		background: #fff;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tabs-scroll {
		white-space: nowrap;
	}

	.tabs-container {
		display: flex;
		padding: 20rpx;
		gap: 20rpx;
	}

	.category-tab {
		padding: 15rpx 30rpx;
		border-radius: 25rpx;
		font-size: 26rpx;
		color: #666;
		background: #f5f5f5;
		white-space: nowrap;
	}

	.category-tab.active {
		background: #8E8E93;
		color: #fff;
	}

	/* 文件列表 */
	.files-list {
		padding: 20rpx;
	}

	.list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.list-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.sort-options {
		display: flex;
		gap: 20rpx;
	}

	.sort-option {
		padding: 10rpx 20rpx;
		border-radius: 15rpx;
		font-size: 24rpx;
		color: #666;
		background: #fff;
	}

	.sort-option.active {
		background: #8E8E93;
		color: #fff;
	}

	.files-scroll {
		max-height: 60vh;
	}

	.file-item {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.file-icon {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.file-info {
		flex: 1;
	}

	.file-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.file-meta {
		display: flex;
		gap: 20rpx;
		margin-bottom: 8rpx;
	}

	.file-size, .file-time {
		font-size: 24rpx;
		color: #666;
	}

	.file-uploader {
		margin-top: 8rpx;
	}

	.uploader-text {
		font-size: 24rpx;
		color: #999;
	}

	.file-actions {
		display: flex;
		gap: 20rpx;
	}

	/* 弹窗样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.modal-content {
		background: #fff;
		border-radius: 16rpx;
		width: 90%;
		max-width: 600rpx;
		max-height: 80vh;
	}

	.modal-header {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.modal-body {
		padding: 30rpx;
		max-height: 60vh;
		overflow-y: auto;
	}

	.upload-area {
		border: 2rpx dashed #ddd;
		border-radius: 16rpx;
		padding: 60rpx 40rpx;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.upload-text {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin: 20rpx 0 10rpx;
	}

	.upload-hint {
		font-size: 24rpx;
		color: #999;
	}

	.selected-file {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.file-preview {
		display: flex;
		align-items: center;
		gap: 15rpx;
		margin-bottom: 10rpx;
	}

	.preview-name {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
	}

	.preview-size {
		font-size: 24rpx;
		color: #666;
	}

	.input-group {
		margin-bottom: 30rpx;
	}

	.input-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
		display: block;
	}

	.textarea-field {
		width: 100%;
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		background: #f9f9f9;
		min-height: 120rpx;
		resize: none;
	}

	.char-count {
		font-size: 24rpx;
		color: #999;
		text-align: right;
		margin-top: 10rpx;
	}

	.picker-field {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		background: #f9f9f9;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.modal-footer {
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		gap: 20rpx;
	}

	.modal-btn {
		flex: 1;
		padding: 20rpx;
		border-radius: 8rpx;
		text-align: center;
	}

	.cancel-btn {
		background: #f0f0f0;
	}

	.confirm-btn {
		background: #8E8E93;
	}

	.btn-text {
		font-size: 28rpx;
		color: #333;
	}

	.confirm-btn .btn-text {
		color: #fff;
	}
</style>


